<template>
  <div class="p-6">
    <div class="mb-6">
      <h1 class="text-2xl font-bold mb-2">知识审核</h1>
      <p class="text-gray-600">审核知识图谱中的实体关系和标签信息</p>
    </div>

    <!-- 操作栏 -->
    <div class="mb-4 flex justify-between items-center">
      <div class="flex gap-2">
        <a-button
          type="primary"
          @click="generateGraphAfterApproval"
          :disabled="tableData.filter((item) => item.status === 'approved').length === 0"
        >
          生成图谱 ({{ tableData.filter((item) => item.status === 'approved').length }})
        </a-button>
      </div>
      <!-- <div class="flex gap-2">
        <a-button @click="exportData">导出数据</a-button>
      </div> -->
    </div>

    <!-- 搜索和筛选区域 -->
    <a-card class="mb-4">
      <a-row :gutter="16">
        <a-col :span="6">
          <a-input-search
            v-model:value="searchText"
            placeholder="搜索文档来源、实体或关系"
            @search="handleSearch"
            allow-clear
          />
        </a-col>
        <a-col :span="4">
          <a-select
            v-model:value="statusFilter"
            placeholder="审核状态"
            allow-clear
            style="width: 100%"
            @change="handleFilter"
          >
            <a-select-option value="">全部</a-select-option>
            <a-select-option value="pending">待审核</a-select-option>
            <a-select-option value="approved">已通过</a-select-option>
            <a-select-option value="rejected">未通过</a-select-option>
          </a-select>
        </a-col>
        <a-col :span="4">
          <a-select
            v-model:value="tagFilter"
            placeholder="标签筛选"
            allow-clear
            style="width: 100%"
            @change="handleFilter"
          >
            <a-select-option value="">全部标签</a-select-option>
            <a-select-option value="供应商">供应商</a-select-option>
            <a-select-option value="质量">质量</a-select-option>
            <a-select-option value="责任人">责任人</a-select-option>
            <a-select-option value="问题">问题</a-select-option>
          </a-select>
        </a-col>
        <a-col :span="6">
          <a-range-picker v-model:value="dateRange" style="width: 100%" @change="handleFilter" />
        </a-col>
      </a-row>
    </a-card>

    <!-- 批量操作栏 -->
    <a-card class="mb-4" v-if="selectedRowKeys.length > 0">
      <a-space>
        <span>已选择 {{ selectedRowKeys.length }} 项</span>
        <a-button type="primary" @click="batchApprove"> 批量通过 </a-button>
        <a-button danger @click="batchReject"> 批量拒绝 </a-button>
      </a-space>
    </a-card>

    <!-- 数据表格 -->
    <div class="h-[calc(100vh-400px)] overflow-hidden">
      <a-table
        :columns="columns"
        :data-source="currentPageData"
        :loading="loading"
        :pagination="paginationConfig"
        :row-selection="rowSelection"
        :scroll="{ y: 'calc(100vh - 500px)' }"
        row-key="id"
        size="middle"
        @change="handleTableChange"
        bordered
        class="scrollBarY"
      >
        <!-- 文档来源列 -->
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'source'">
            <a-tooltip :title="record.source">
              <div
                style="
                  max-width: 200px;
                  overflow: hidden;
                  text-overflow: ellipsis;
                  white-space: nowrap;
                "
              >
                {{ record.source }}
              </div>
            </a-tooltip>
          </template>

          <!-- 实体1列 -->
          <template v-else-if="column.key === 'entity1'">
            <a-tag color="blue">{{ record.entity1 }}</a-tag>
          </template>

          <!-- 关系列 -->
          <template v-else-if="column.key === 'relation'">
            <a-tag color="green">{{ record.relation }}</a-tag>
          </template>

          <!-- 实体2列 -->
          <template v-else-if="column.key === 'entity2'">
            <a-tag color="blue">{{ record.entity2 }}</a-tag>
          </template>

          <!-- 切片列 -->
          <template v-else-if="column.key === 'chunk'">
            <div style="max-width: 300px">
              <a-tooltip :title="record.chunk">
                <div style="overflow: hidden; text-overflow: ellipsis; white-space: nowrap">
                  {{ record.chunk }}
                </div>
              </a-tooltip>
              <a-button type="link" size="small" @click="showChunkDetail(record)">
                查看详情
              </a-button>
            </div>
          </template>

          <!-- 标签列 -->
          <template v-else-if="column.key === 'tags'">
            <a-space wrap>
              <a-tag v-for="tag in record.tags" :key="tag" :color="getTagColor(tag)">
                {{ tag }}
              </a-tag>
            </a-space>
          </template>

          <!-- 审核结果列 -->
          <template v-else-if="column.key === 'status'">
            <a-tag
              :color="
                record.status === 'approved'
                  ? '#00c950'
                  : record.status === 'rejected'
                    ? '#fb2c36'
                    : '#fe9a00'
              "
            >
              {{
                record.status === 'approved'
                  ? '通过'
                  : record.status === 'rejected'
                    ? '不通过'
                    : '待审核'
              }}
            </a-tag>
          </template>

          <!-- 操作列 -->
          <template v-else-if="column.key === 'action'">
            <a-space>
              <a-button
                type="link"
                size="small"
                :disabled="record.status !== 'pending'"
                @click="approveItem(record)"
              >
                通过
              </a-button>
              <a-button
                type="link"
                size="small"
                danger
                :disabled="record.status !== 'pending'"
                @click="rejectItem(record)"
              >
                拒绝
              </a-button>
              <a-button type="link" size="small" @click="editItem(record)"> 编辑 </a-button>
              <a-popconfirm title="确认删除？" @confirm="deleteItem(record)">
                <template #icon><question-circle-outlined style="color: red" /></template>
                <a-button type="link" size="small">
                  <span style="color: #ff4d4f">删除</span>
                </a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </div>
    <!-- 切片详情弹窗 -->
    <a-modal v-model:open="chunkModalVisible" title="切片详情" width="800px" :footer="null">
      <div v-if="currentChunk">
        <a-descriptions :column="1" bordered>
          <a-descriptions-item label="文档来源">
            {{ currentChunk.source }}
          </a-descriptions-item>
          <a-descriptions-item label="实体关系">
            <a-space>
              <a-tag color="blue">{{ currentChunk.entity1 }}</a-tag>
              <span>→</span>
              <a-tag color="green">{{ currentChunk.relation }}</a-tag>
              <span>→</span>
              <a-tag color="blue">{{ currentChunk.entity2 }}</a-tag>
            </a-space>
          </a-descriptions-item>
          <a-descriptions-item label="标签">
            <a-space wrap>
              <a-tag v-for="tag in currentChunk.tags" :key="tag" :color="getTagColor(tag)">
                {{ tag }}
              </a-tag>
            </a-space>
          </a-descriptions-item>
          <a-descriptions-item label="完整内容">
            <div
              style="
                max-height: 200px;
                overflow-y: auto;
                background: #f5f5f5;
                padding: 12px;
                border-radius: 4px;
              "
            >
              {{ currentChunk.chunk }}
            </div>
          </a-descriptions-item>
        </a-descriptions>
      </div>
    </a-modal>

    <!-- 编辑弹窗 -->
    <a-modal v-model:open="editModalVisible" title="编辑审核项" width="600px" @ok="saveEdit">
      <a-form :model="editForm" layout="vertical">
        <a-form-item label="实体1">
          <a-input v-model:value="editForm.entity1" />
        </a-form-item>
        <a-form-item label="关系">
          <a-input v-model:value="editForm.relation" />
        </a-form-item>
        <a-form-item label="实体2">
          <a-input v-model:value="editForm.entity2" />
        </a-form-item>
        <a-form-item label="标签">
          <a-select
            v-model:value="editForm.tags"
            mode="tags"
            placeholder="选择或输入标签"
            style="width: 100%"
          >
            <a-select-option value="供应商">供应商</a-select-option>
            <a-select-option value="质量">质量</a-select-option>
            <a-select-option value="责任人">责任人</a-select-option>
            <a-select-option value="问题">问题</a-select-option>
            <a-select-option value="流程">流程</a-select-option>
            <a-select-option value="合作">合作</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="备注">
          <a-textarea v-model:value="editForm.comment" :rows="3" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { DownOutlined, QuestionCircleOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { deleteKnowledge } from '@/api/api'

// 响应式数据
const loading = ref(false)
const searchText = ref('')
const statusFilter = ref('')
const tagFilter = ref('')
const dateRange = ref([])
const selectedRowKeys = ref([])
const chunkModalVisible = ref(false)
const editModalVisible = ref(false)
const currentChunk = ref(null)
const editForm = ref({})

// 排序和筛选状态
const sortField = ref('')
const sortOrder = ref('')
const tableFilters = ref({})

// 表格列配置
const columns = [
  {
    title: '文档来源',
    dataIndex: 'source',
    key: 'source',
    width: 200,
    ellipsis: true,
  },
  {
    title: '实体1',
    dataIndex: 'entity1',
    key: 'entity1',
    width: 120,
  },
  {
    title: '关系',
    dataIndex: 'relation',
    key: 'relation',
    width: 120,
  },
  {
    title: '实体2',
    dataIndex: 'entity2',
    key: 'entity2',
    width: 120,
  },
  {
    title: '切片',
    dataIndex: 'chunk',
    key: 'chunk',
    width: 300,
    ellipsis: true,
  },
  {
    title: '标签',
    dataIndex: 'tags',
    key: 'tags',
    width: 150,
  },
  {
    title: '审核结果',
    dataIndex: 'status',
    key: 'status',
    width: 100,
    filters: [
      { text: '待审核', value: 'pending' },
      { text: '已通过', value: 'approved' },
      { text: '未通过', value: 'rejected' },
    ],
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    width: 120,
    sorter: true,
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    fixed: 'right',
  },
]

// 模拟数据
const tableData = ref([])

// 筛选后的数据
const filteredData = computed(() => {
  let data = [...tableData.value]

  // 搜索筛选
  if (searchText.value) {
    data = data.filter(
      (item) =>
        item.source.includes(searchText.value) ||
        item.entity1.includes(searchText.value) ||
        item.entity2.includes(searchText.value) ||
        item.relation.includes(searchText.value),
    )
  }

  // 状态筛选
  if (statusFilter.value) {
    data = data.filter((item) => item.status === statusFilter.value)
  }

  // 标签筛选
  if (tagFilter.value) {
    data = data.filter((item) => item.tags.includes(tagFilter.value))
  }

  // 表头筛选
  Object.keys(tableFilters.value).forEach((key) => {
    const filterValues = tableFilters.value[key]
    if (filterValues && filterValues.length > 0) {
      data = data.filter((item) => filterValues.includes(item[key]))
    }
  })

  // 排序
  if (sortField.value && sortOrder.value) {
    data.sort((a, b) => {
      const aVal = a[sortField.value]
      const bVal = b[sortField.value]

      if (sortField.value === 'createTime') {
        const aTime = new Date(aVal).getTime()
        const bTime = new Date(bVal).getTime()
        return sortOrder.value === 'ascend' ? aTime - bTime : bTime - aTime
      }

      if (typeof aVal === 'string') {
        return sortOrder.value === 'ascend' ? aVal.localeCompare(bVal) : bVal.localeCompare(aVal)
      }

      return sortOrder.value === 'ascend' ? aVal - bVal : bVal - aVal
    })
  }

  return data
})

// 分页配置
const paginationConfig = reactive({
  current: 1,
  pageSize: 10,
  total: computed(() => filteredData.value.length),
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
})

// 当前页显示的数据
const currentPageData = computed(() => {
  const start = (paginationConfig.current - 1) * paginationConfig.pageSize
  const end = start + paginationConfig.pageSize
  return filteredData.value.slice(start, end)
})

// 行选择配置
const rowSelection = {
  selectedRowKeys: selectedRowKeys,
  onChange: (keys) => {
    selectedRowKeys.value = keys
  },
}

// 方法
const handleSearch = () => {
  // 搜索逻辑已在计算属性中处理
}

const handleFilter = () => {
  // 筛选逻辑已在计算属性中处理
}

const handleTableChange = (pagination, filters, sorter) => {
  console.log('表格变化:', { pagination, filters, sorter })

  // 更新分页
  paginationConfig.current = pagination.current
  paginationConfig.pageSize = pagination.pageSize

  // 更新筛选
  tableFilters.value = filters

  // 更新排序
  sortField.value = sorter.field || ''
  sortOrder.value = sorter.order || ''
}

// 批量通过后生成图谱
const generateGraphAfterApproval = async () => {
  const approvedItems = tableData.value.filter((item) => item.status === 'approved')

  if (approvedItems.length === 0) {
    message.warning('没有已审核通过的数据，无法生成图谱')
    return
  }

  try {
    message.loading('正在生成知识图谱...', 0)

    // 模拟调用图谱生成API
    await new Promise((resolve) => setTimeout(resolve, 3000))

    message.destroy()
    message.success(`基于 ${approvedItems.length} 条审核通过的数据生成图谱成功！`)

    // 跳转到图谱查看页面
    setTimeout(() => {
      window.location.href = '#/graph/overview'
    }, 1500)
  } catch (error) {
    message.destroy()
    message.error('图谱生成失败！')
  }
}

const batchApprove = () => {
  const pendingItems = selectedRowKeys.value.filter((id) => {
    const item = tableData.value.find((item) => item.id === id)
    return item && item.status === 'pending'
  })

  if (pendingItems.length === 0) {
    message.warning('没有可审核的项目')
    return
  }

  pendingItems.forEach((id) => {
    const item = tableData.value.find((item) => item.id === id)
    if (item) item.status = 'approved'
  })

  message.success(`批量通过 ${pendingItems.length} 项`)
  selectedRowKeys.value = []

  // 检查是否有足够的审核通过数据，提示生成图谱
  const approvedCount = tableData.value.filter((item) => item.status === 'approved').length
  if (approvedCount >= 3) {
    setTimeout(() => {
      message.info('已有足够的审核数据，可以生成知识图谱了！')
    }, 1000)
  }
}

const batchReject = () => {
  const pendingItems = selectedRowKeys.value.filter((id) => {
    const item = tableData.value.find((item) => item.id === id)
    return item && item.status === 'pending'
  })

  if (pendingItems.length === 0) {
    message.warning('没有可审核的项目')
    return
  }

  pendingItems.forEach((id) => {
    const item = tableData.value.find((item) => item.id === id)
    if (item) item.status = 'rejected'
  })

  message.success(`批量拒绝 ${pendingItems.length} 项`)
  selectedRowKeys.value = []
}

const approveItem = (record) => {
  record.status = 'approved'
  message.success('审核通过')
}

const rejectItem = (record) => {
  record.status = 'rejected'
  message.success('审核拒绝')
}

const showChunkDetail = (record) => {
  currentChunk.value = record
  chunkModalVisible.value = true
}

const editItem = (record) => {
  editForm.value = { ...record }
  editModalVisible.value = true
}

const saveEdit = () => {
  const index = tableData.value.findIndex((item) => item.id === editForm.value.id)
  if (index > -1) {
    tableData.value[index] = { ...editForm.value }
  }
  message.success('保存成功')
  editModalVisible.value = false
}

const deleteItem = async (record) => {
  console.log('🐯 ~ deleteItem ~ record:', record)
  const res = await deleteKnowledge({
    id_list: [record.id],
  })
  const index = tableData.value.findIndex((item) => item.id === record.id)
  if (index > -1) {
    tableData.value.splice(index, 1)
    message.success('删除成功')
  }
}

const getTagColor = (tag) => {
  const colors = {
    供应商: 'blue',
    问题事件: 'green',
    责任人: 'orange',
    零部件: 'purple',
    发起人: 'cyan',
  }
  return colors[tag] || 'default'
}

// 在onMounted中添加检查新数据的逻辑
onMounted(() => {
  // 检查是否有新的提取数据
  const latestData = sessionStorage.getItem('latestExtractedData')
  if (latestData) {
    try {
      const extractedData = JSON.parse(latestData)

      // 将新提取的数据添加到表格数据的开头
      if (extractedData.extractedRelations && extractedData.extractedRelations.length > 0) {
        // 在现有数据前插入新数据
        tableData.value.unshift(...extractedData.extractedRelations)

        message.success(
          `已加载来自 ${extractedData.fileName} 的 ${extractedData.extractedRelations.length} 条新提取的实体关系`,
        )
      }

      // 清除sessionStorage中的数据，避免重复加载
      sessionStorage.removeItem('latestExtractedData')
    } catch (error) {
      console.error('解析提取数据失败:', error)
    }
  }
})
</script>

<style lang="scss" scoped></style>
